package com.initialize.pub.token;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.initialize.pub.config.SiteConfig;
import com.initialize.pub.dao.UserDAO;
import com.initialize.pub.exception.TokenException;
import com.initialize.pub.generate.pojo.User;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@Service
public class TokenService {


    private final
    UserDAO userDAO;

    // 过期时间，单位毫秒
    private static final long EXPIRE_TIME = 7 * 24 * 3600 * 1000;


    public TokenService(UserDAO userDAO) {
        this.userDAO = userDAO;
    }

    /**
     * 获取生成的token
     *
     * @param user
     * @return
     */
    public String getToken(User user) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String token;
        try {
            token = JWT.create()
                    .withAudience(String.valueOf(user.getUid()))
                    .withExpiresAt(date)
                    .sign(Algorithm.HMAC256(user.getPsd()));
            return token;
        } catch (Exception e) {
            token = "非法参数";
        }
        return token;
    }

    /**
     * 获取网络请求的token
     *
     * @param httpServletRequest
     * @return
     */
    public String getUserToken(HttpServletRequest httpServletRequest) {
        return httpServletRequest.getHeader("user_token");
    }

    /**
     * 通过网络请求的token直接返回当前有效的操作者id
     *
     * @param httpServletRequest
     * @return
     */
    public int getId(HttpServletRequest httpServletRequest) throws TokenException {
        String userToken = getUserToken(httpServletRequest);

        if (SiteConfig.FLAG) {
            if (userToken.equals(TokenUtil.TOKEN_TEST_TOKEN)) {
                return 2;
            }
        }


        int Id;
        try {
            Id = Integer.parseInt(JWT.decode(userToken)
                    .getAudience()
                    .get(0));
        } catch (JWTDecodeException j) {
            throw new TokenException("401");
        }
        return Id;
    }


}
